package network;


import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

//客户端的练习
public class UdpEchoClientExercise {
    //定义一个socket对象
    private DatagramSocket socket = null;
    private String serverIP;  //服务器IP
    private int serverPort ;  //服务器端口

    public UdpEchoClientExercise(String serverIP,int serverPort) throws SocketException {
        socket = new DatagramSocket();

        this.serverIP = serverIP;
        this.serverPort = serverPort;
    }

    //客户端启动
    public void start() throws IOException {
        Scanner scanner = new Scanner(System.in);

        while(true) {
            System.out.println("请输入请求：");
            String request = scanner.nextLine();

            // 1.发送请求  注意DatagramPacket 的构造方法参数
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length,
                    InetAddress.getByName(serverIP),serverPort);
            socket.send(requestPacket);

            // 2.接受响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);

            // 3. 把响应数据转换成 String 显示出来.
            String response = new String(responsePacket.getData(),0, responsePacket.getLength());
            System.out.println("req: " + request + " resp: " + response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClientExercise udpEchoClientExercise = new UdpEchoClientExercise("127.0.0.1", 9090);
        udpEchoClientExercise.start();
    }
}
